import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login' // 重定向
  },
  {
    path: '/login',
    component: () => import('@/components/login.vue')
  },
  {
    path: '/home',
    component: () => import('@/components/home.vue'),
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: () => import('@/components/welcome.vue') },
      { path: '/users', component: () => import('@/components/user/user.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载路由守卫
router.beforeEach((to, from, next) => {
  const token = window.sessionStorage.getItem('token')
  if (to.path === '/login') {
    return next()
  }
  // 没有token让去登录页
  if (!token) return next('/login')
  // 有的话放行
  next()
})
export default router
